package com.supply.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.supply.pojo.PasswordData;
import com.supply.pojo.ResultBean;
import com.supply.pojo.User;
import com.supply.req.UserReq;
import com.supply.service.UserService;
import org.apache.ibatis.annotations.Delete;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("list")
//    @RequiresPermissions("/personnel/user")
    public ResultBean list(UserReq userReq){
        System.out.println("请求的数据：" + userReq);
        PageHelper.startPage(userReq.getPageNum(),userReq.getPageSize());
        List<User> users = userService.queryByCondition(userReq);
        return ResultBean.success(new PageInfo(users));
    }

    @GetMapping("/queryAll")
    public ResultBean queryAll(){
        return ResultBean.success(userService.queryAll());
    }

    @PostMapping("/saveOrUpdate")
    public ResultBean saveOrUpdate(@RequestBody User user){
        System.out.println("新增或修改的数据：" + user);
        int rs = userService.saveOrUpdate(user);
        return rs >= 1 ? ResultBean.success() : ResultBean.error("服务器异常");
    }

    @DeleteMapping("/delete/{id}")
    public ResultBean delete(@PathVariable("id") Long id){
        System.out.println("要删除的用户id:" + id);
        int rs = userService.deleteById(id);
        return rs >= 1 ? ResultBean.success() : ResultBean.error("服务器异常");
    }


    //修改密码
    @PostMapping("/updatePassword")
    public ResultBean updatePassword(@RequestBody PasswordData passwordData){
        System.out.println("密码数据：" + passwordData);
        User user = userService.queryById(passwordData.getId());
        Md5Hash oldPassword = new Md5Hash(passwordData.getOldPassword(),user.getUsercode(),3);
        Md5Hash newPassword = new Md5Hash(passwordData.getNewPassword(),user.getUsercode(),3);
        if (user.getPassword().equals(oldPassword.toString())) {
            user.setPassword(newPassword.toString());
            int rs = userService.updateById(user);
            return rs >= 1 ? ResultBean.success() : ResultBean.error("服务器异常");
        }else {
            return ResultBean.error("原始密码错误，请重新输入");
        }
    }

    //更换头像
    @GetMapping("/switchAvatar")
    public ResultBean switchAvatar(Long id, String avatar){
        System.out.println("UserID：" + id);
        System.out.println("url:" + avatar);
        User user = userService.queryById(id);
        user.setAvatar(avatar);
        int rs = userService.updateById(user);
        return rs >= 1 ? ResultBean.success(user) : ResultBean.error("服务器异常");

    }
}
